package com.wjd.wshow.controller;

import com.wjd.wshow.bean.VideoSearchBean;
import com.wjd.wshow.common.resource.ResourceType;
import com.wjd.wshow.common.resource.entity.ImageResource;
import com.wjd.wshow.common.resource.loader.Uploader;
import com.wjd.wshow.common.resource.pojo.UploadResource;
import com.wjd.wshow.entity.Image;
import com.wjd.wshow.service.ImageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@ResponseBody
@RequestMapping("/images")
@RestController("ImageController")
public class ImageController {

    private static Logger logger = LoggerFactory.getLogger(ImageController.class);

    @javax.annotation.Resource(name = "ImageService")
    private ImageService imageService;

    @GetMapping("/list_all")
    public List<Image> getListImages() {
        return imageService.getImages();
    }

    @PostMapping("/list")
    public List<Image> listImages(@RequestBody VideoSearchBean bean) {
        if (bean.getPath() == null) {
            throw new IllegalArgumentException();
        }
        return imageService.findImages(bean.getPath());
    }

    @PostMapping("/upload")
    public final String uploadImage(@RequestParam(name = "file") MultipartFile file,
                                    @RequestParam(name = "path", defaultValue = "") String path) {
        if (file == null || file.isEmpty()) {
            return null;
        }

        try {
            // 上传文件信息
            String contentType = file.getContentType();
            String filename = file.getOriginalFilename();
            Path filePath = Paths.get(path, filename);

            // 上传资源
            UploadResource uploadResource = new UploadResource();
            uploadResource.setType(ResourceType.IMAGE);
            uploadResource.setFilename(filename);
            uploadResource.setPath(filePath);
            uploadResource.setInputStream(file.getInputStream());
            uploadResource.setSize(file.getSize());

            // 上传
            new Uploader().upload(uploadResource);
            Path uploadPath = uploadResource.getPath();
            logger.info("upload file path: " + uploadPath);

            // 保存数据库
            Image image = new Image();
            image.setType(contentType);
            image.setName(filename);
            image.setPath(uploadPath.toString());
            imageService.addImage(image);
            return image.getId();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getCause().getMessage());
        }

        return null;
    }

    /**
     * 获取图片
     * @param id 图片id
     * @param response 响应对象
     */
    @GetMapping("/{id}")
    public final void downloadImage(@PathVariable String id, HttpServletResponse response) {
        try {
            ImageResource imageResource = (ImageResource) imageService.getResource(id);
            if (imageResource == null || !imageResource.exist()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 返回图片
            response.setHeader("Content-Type", "image/png");
            response.setHeader("Content-Length", String.format("%d", imageResource.getSize()));
            new Uploader().download(imageResource, response.getOutputStream());
        } catch (Exception e) {
            logger.error(e.getCause().getMessage());
        }
    }

    /**
     * 删除图片
     * @param id 图片id
     */
    @DeleteMapping("/{id}")
    public final void deleteImage(@PathVariable String id) {
        imageService.deleteImage(id);
    }
}
